package org.example.base;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class BaseConsumer {
    public static void main(String[] args) throws Exception {

        // 1、创建消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("my-consumer-group1");

        // 2、指定nameserver地址
        consumer.setNamesrvAddr("192.168.2.10:9876");

        // 3、订阅主题及过滤消息（通过tag过滤）
        consumer.subscribe("MyTopic1", "*");

        // 4、创建监听器，监听broker推送的消息
        consumer.registerMessageListener((MessageListenerConcurrently) (msgs, consumeConcurrentlyContext) -> {

            // 消费消息
            for (MessageExt msg : msgs) {
                System.out.println("收到消息：" + new String(msg.getBody()));
            }

            // 告知消费结果
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        // 5、启动消费者
        consumer.start();
        System.out.println("启动消费者");

    }
}
